package com.liu.my_blog_system.utils;

import com.liu.my_blog_system.entity.TbUser;
import com.liu.my_blog_system.service.TbUserService;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.Map;

@Data
@Component
@ConfigurationProperties("blog.jwt.config")
public class JwtUtils {

    public static final String ID = "id";
    public static final String USERNAME = "username";
    public static final String ROLES = "roles";
    public static final String AVATAR = "avatar";
    public static final String EMAIL = "email";
    public static final String SIGN = "sign";
    /**
     * 私钥
     */
    private static String key;
    @Value("${blog.jwt.config.key}")
    public void setKey(String key) {
        JwtUtils.key = key;
    }
    /**
     * token失效时间
     */
    private static Long ttl;
    @Value("${blog.jwt.config.ttl}")
    public void setTtl(Long ttl) {
        JwtUtils.ttl = ttl;
    }

    private static TbUserService userService;
    @Autowired
    public void setUserService(TbUserService userService) {
        JwtUtils.userService = userService;
    }
    /**
     * 生成token
     *
     * @param claims 参数
     * @return token
     */
    public static String createJwt(Map<String, Object> claims) {
        // 设置失效时间
        long nowMills = System.currentTimeMillis();
        // 创建 JwtBuilder
        JwtBuilder jwtBuilder = Jwts.builder()
                .setIssuedAt(new Date(nowMills))
                .signWith(SignatureAlgorithm.HS256, key);
        // 设置claims
        if (claims != null) {
            jwtBuilder.setClaims(claims);
        }
        //设置过期时间
        if (ttl > 0) {
            jwtBuilder.setExpiration(new Date(ttl+nowMills));
        }
        // 生成token
        return jwtBuilder.compact();
    }

    /**
     * 生成refresh_token
     * @param id
     * @param ttl
     * @return
     */
    public static String createRefreshToken(String id, Long ttl) {
        long nowMills = System.currentTimeMillis();
        JwtBuilder jwtBuilder = Jwts.builder()
                .setId(id)
                .setIssuedAt(new Date(nowMills))
                .signWith(SignatureAlgorithm.HS256,key);
        //设置过期时间
        if (ttl > 0) {
            jwtBuilder.setExpiration(new Date(ttl + nowMills));
        }
        //生成token
        return jwtBuilder.compact();
    }
    /**
     * 解析token 获取Claims
     *
     * @param token jwt生成的token
     * @return Claims
     */
    public static Claims parseJwt(String token) {
        return Jwts.parser().setSigningKey(key).parseClaimsJws(token).getBody();
    }

    /**
     * 把claims对象转换成user对象
     * @param claims
     * @return
     */
    public static TbUser claimsToUser(Claims claims) {
        TbUser user = new TbUser();
        user.setId((String) claims.get(ID));
        user.setUsername((String) claims.get(USERNAME));
        user.setRoles((String) claims.get(ROLES));
        user.setAvatar((String) claims.get(AVATAR));
        user.setEmail((String) claims.get(EMAIL));
        user.setSign((String) claims.get(SIGN));
        return user;
    }

    /**
     * 判断是否是管理员
     * @param request
     * @param response
     * @return
     */
    public static boolean isAdmin(HttpServletRequest request, HttpServletResponse response) {
        Map map = userService.checkUserStatus(request, response);
        TbUser userInfo = (TbUser)map.get("userInfo");
        if (userInfo == null || !userInfo.getRoles().equals(Constants.User.ADMIN)) {
            return false;
        }
        return true;
    }
}
